<template>
  <el-card>
    <el-line title="新增专班"></el-line>
    <el-form style="margin-top: 10px;" :label-width="labelwidth" ref="classRef" :rules="classRules" :model="classForm" class="demo-form-inline">
      <el-row>
        <el-col :span="12">
          <el-form-item label="专班名称" prop="specializedClassName">
            <el-input v-model="classForm.specializedClassName" placeholder="请输入专班名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="组长" prop="groupLeaderId">
            <el-select
                filterable
                @change="userChange"
                v-model="classForm.groupLeaderId"
                placeholder="请选择组长"
                clearable
            >
              <el-option v-for="user in users" :key="user.user_id" :value="user.user_id" :label="user.nick_name"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="成立文件">
            <el-upload
                v-model:file-list="fileList"
                class="upload-demo"
                :action="uploadFileUrl"
                :headers="headers"
                multiple
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                :on-exceed="handleExceed"
            >
              <el-button>选择文件</el-button>
              <template #tip>
                <div class="el-upload__tip">
<!--                  jpg/png files with a size less than 500KB.-->
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <div style="text-align: center">
        <el-button class="btnWidth" type="primary" @click="onSubmit">保存</el-button>
        <el-button class="btnWidth" type="info" @click="classFormRest">清空</el-button>
      </div>
    </el-form>
  </el-card>
  <el-card style="margin-top: 20px">
    <el-form  ref="classParamRef" :model="classParamForm" class="demo-form-inline">
      <el-row>
        <el-col :span="7" :offset="1">
          <el-form-item label="专班名称">
            <el-input v-model="classParamForm.specializedClassName" placeholder="请输入专班名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="7" :offset="1">
          <el-select
              filterable
              v-model="classParamForm.groupLeaderId"
              placeholder="请选择组长"
              clearable
          >
            <el-option v-for="user in users" :key="user.user_id" :value="user.user_id" :label="user.nick_name"/>
          </el-select>
        </el-col>
        <el-col :span="7" :offset="1">
          <el-button class="btnWidth" type="primary" @click="getList">查询</el-button>
          <el-button class="btnWidth" type="info" @click="classParamFormRest">重置</el-button>
        </el-col>
      </el-row>
    </el-form>
    <el-row style="margin-bottom: 10px;">
      <el-button class="btnWidth" type="danger" @click="delClassM">删除</el-button>
      <el-button class="btnWidth"  type="warning" @click="exportClass">导出</el-button>
    </el-row>
    <el-table
        ref="multipleTableRef"
        :data="tableData"
        style="width: 100%"
        :row-class-name="tableRowClassName"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection"/>
      <el-table-column type="index" width="100" label="序号"/>
      <el-table-column property="specializedClassName" label="专班名称"/>
      <el-table-column property="systemFile" label="成立文件">
        <template #default="scope">
          <el-link icon="el-icon-document-remove" style="display: block;color: #577cfa"
                   v-for=" img in tableData[scope.row.index].workFiles"
                   :href="img.fileUrl" target="_blank" :download="img.fileName">
            {{ img.fileName }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column property="groupLeader" label="组长"/>
      <el-table-column property="assistantGroupLeaderNames" label="副组长"/>
      <el-table-column property="members" label="成员">
        <!--        <template #default="scope">-->
        <!--          <dict-tag :options="system_type" :value="scope.row.systemType"/>-->
        <!--        </template>-->
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">成员管理
          </el-button>
          <el-button  v-if="scope.row.parentId != 0" link type="primary" icon="Delete"
                     @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="classParamForm.pageNum"
        v-model:limit="classParamForm.pageSize"
        @pagination="getList"
    />

    <el-dialog draggable align-center v-model="openClass" title="专班成员管理"
               style="margin-top: 200px !important;">
      <el-form  ref="systemUpdateRef" :rules="classRules" :model="classViewForm" class="demo-form-inline"
               :label-width="labelwidth">
        <el-row>
          <el-col :span="24">
            <el-form-item label="专班名称" prop="specializedClassName">
              <el-input v-model="classViewForm.specializedClassName" placeholder="请输入专班名称"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="组长" prop="groupLeaderId">
              <el-select
                  filterable
                  @change="userUpdateChange"
                  v-model="classViewForm.groupLeaderId"
                  placeholder="请选择组长"
              >
                <el-option v-for="user in users" :key="user.user_id" :value="user.user_id" :label="user.nick_name"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="部门" prop="specializedClassName">
              <el-input disabled v-model="classViewForm.groupLeaderDeptName"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="职务" prop="specializedClassName">
              <el-input disabled v-model="classViewForm.groupLeaderPostName"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="制度文件">
              <el-upload
                  v-model:file-list="fileViewList"
                  class="upload-demo"
                  :action="uploadFileUrl"
                  :headers="headers"
                  multiple
              >
                <el-button>选择文件</el-button>
                <template #tip>
                  <div class="el-upload__tip">
<!--                    jpg/png files with a size less than 500KB.-->
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-line title="副职维护"/>
      <el-table
          size="small"
          :row-class-name="tableRowClassName"
          :data="tableUpdateData1"
          highlight-current-row
          style="width: 100%;margin-top: 10px;"
          @current-change="handleUpdateSelectionChange"
      >
        <el-table-column type="index" label="序号" width="50"/>
        <el-table-column property="groupLeader" label="姓名">
          <template #default="scope">
            <el-select
                filterable
                @change="userUpdateFzChange($event, scope.row.index,1)"
                v-model="tableUpdateData1[scope.row.index].userId"
                placeholder="请选择副组长"
            >
              <el-option v-for="user in users" :key="user.user_id" :value="user.user_id" :label="user.nick_name"/>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column property="groupLeaderDeptName" label="部门">
          <template #default="scope">
            <el-input v-model="tableUpdateData1[scope.row.index].groupLeaderDeptName" disabled></el-input>
          </template>
        </el-table-column>
        <el-table-column property="groupLeaderPostName" label="职务">
          <template #default="scope">
            <el-input v-model="tableUpdateData1[scope.row.index].groupLeaderPostName" disabled></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button icon="Refresh" link type="primary" @click="clearUpdateTable(scope.row.index,1)">清空</el-button>
            <el-button icon="delete" link type="primary" @click="delUpdateTable(scope.row.index,1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: center;margin-top: 10px;">
        <el-button type="text" icon="CirclePlus" @click="addUpdateTableData(1)">添加</el-button>
      </div>
      <el-line title="成员维护"/>
      <el-table
          size="small"
          :row-class-name="tableRowClassName"
          :data="tableUpdateData2"
          highlight-current-row
          style="width: 100%;margin-top: 10px;"
          @current-change="handleUpdateSelectionChange"
      >
        <el-table-column type="index" label="序号" width="50"/>
        <el-table-column property="groupLeader" label="姓名">
          <template #default="scope">
            <el-select
                filterable
                @change="userUpdateFzChange($event, scope.row.index,2)"
                v-model="tableUpdateData2[scope.row.index].userId"
                placeholder="请选择成员"
            >
              <el-option v-for="user in users" :key="user.user_id" :value="user.user_id" :label="user.nick_name"/>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column property="groupLeaderDeptName" label="部门">
          <template #default="scope">
            <el-input v-model="tableUpdateData2[scope.row.index].groupLeaderDeptName" disabled></el-input>
          </template>
        </el-table-column>
        <el-table-column property="groupLeaderPostName" label="职务">
          <template #default="scope">
            <el-input v-model="tableUpdateData2[scope.row.index].groupLeaderPostName" disabled></el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button icon="Refresh" link type="primary" @click="clearUpdateTable(scope.row.index,2)">清空</el-button>
            <el-button  icon="delete" link type="primary"  @click="delUpdateTable(scope.row.index,2)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: center;margin-top: 10px;">
        <el-button type="text" icon="CirclePlus" @click="addUpdateTableData(2)">添加</el-button>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="updateClassM">
            保存
          </el-button>
          <el-button @click="openClass = false">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>


</template>
<script setup>

const {proxy} = getCurrentInstance();
import {reactive, ref} from 'vue'
import {addClass, getUsers, list, getInfo, getDeptAndPostByUserId,updateClass,delClass} from "../../../api/jobAid/specialized_class_manage.js";
import {getToken} from "@/utils/auth";
import {downloadByBlob} from "../../../utils/ruoyi.js";
const ids = ref([]);
let labelwidth = 80;
let tableData = ref([]);
let tableUpdateData1 = ref([]);
let tableUpdateData2 = ref([]);
const total = ref(0);
let openClass = ref(false);

const headers = ref({Authorization: "Bearer " + getToken()});
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload"); // 上传文件服务器地址
const classData = reactive({
  classForm: {
    specializedClassName: '',
    groupLeaderId: '',
    groupLeader: ''
  },
  classRules: {
    specializedClassName: [{required: true, message: "专班名称不能为空", trigger: "blur"}],
    groupLeaderId: [{required: true, message: "请选择组长", trigger: "change"}],
  },
  classParamForm: {
    pageNum: 1,
    pageSize: 10,
    specializedClassName: '',
    groupLeaderId: '',
  },
  classViewForm: {
    specializedClassName: '',
    groupLeader: '',
    groupLeaderId: '',
    groupLeaderDeptName: '',
    groupLeaderPostName: '',
  },
});
let users = ref([]);
const fileList = ref([]);
const fileViewList = ref([]);
const {classForm, classRules, classParamForm, classViewForm} = toRefs(classData);

function addUpdateTableData(type) {
  switch (type) {
    case 1 :
      tableUpdateData1.value.push({});
      break;
    case 2 :
      tableUpdateData2.value.push({});
      break;
  }
}
//导出
function exportClass() {
  classParamForm.value.ids = ids.value;
  proxy.download("jobAid/classManage/export", {
    ...classParamForm.value,
  }, `job_${new Date().getTime()}.xlsx`);
  classParamForm.value.ids = null;
}
function delClassM(){
  if (ids.value.length == 0) {
    proxy.$modal.msgWarning("请选择要删除的数据");
    return;
  }
  proxy.$modal.confirm('是否确认删除?').then(function () {
    return delClass(ids.value);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

function handleDelete(row){
  proxy.$modal.confirm('是否确认删除?').then(function () {
    return delClass(row.sid);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}
function updateClassM(){
  classViewForm.value.fileList = fileViewList;
  classViewForm.value.workSpecializedClassManageUserList = [...tableUpdateData1.value,...tableUpdateData2.value]
  updateClass(classViewForm.value).then((res) => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess("操作成功");
      getList();
      openClass.value = false;
    }
  })
}

function classFormViewRest(){
  classViewForm.value = {};
  fileViewList.value = [];
  tableUpdateData1.value = [];
  tableUpdateData2.value = [];
}

//编辑
function handleUpdate(row) {
  classFormViewRest();
  getInfo(row.sid).then((res) => {
    let tableData = res.data.workSpecializedClassManageUserList;
    tableUpdateData1.value= tableData.filter(item => item.userType == '1');
    tableUpdateData2.value= tableData.filter(item => item.userType == '2');
    if (tableUpdateData1.value.length == 0) {
      tableUpdateData1.value[0] = {}
    }
    if (tableUpdateData2.value.length == 0) {
      tableUpdateData2.value[0] = {}
      console.log(tableUpdateData2)
    }
    classViewForm.value = res.data;
    fileViewList.value = res.data.workFiles.map(t => {
      var obj = {}
      obj.url = t.fileUrl
      obj.name = t.fileName
      obj.filePath = t.filePath
      return obj
    })
    openClass.value = true;
  })
}
function clearUpdateTable(index,type) {
  switch (type) {
    case 1 :
      tableUpdateData1.value[index] = {};
      break;
    case 2 :
      tableUpdateData2.value[index] = {};
      break;
  }
}

function delUpdateTable(index,type) {
  switch (type) {
    case 1 :
      tableUpdateData1.value.splice(index, 1)
      break;
    case 2 :
      tableUpdateData2.value.splice(index, 1)
      break;
  }
}

function userChange(userId) {
  const label = users.value.find(item => item.user_id == userId).nick_name;
  classForm.value.groupLeader = label;
  console.log(label);
}

function userUpdateChange(userId) {
  const label = users.value.find(item => item.user_id == userId).nick_name;
  classViewForm.value.groupLeader = label;
  getDeptAndPostByUserIdM(userId, classViewForm.value);
}

function userUpdateFzChange(userId, index,type) {
  getDeptAndPostByUserId({userId}).then((res) => {
    if (res.code == 200) {
      let tableData = tableUpdateData1;
      switch (type) {
        case 2:
          tableData = tableUpdateData2;
          break;
      }
      const label = users.value.find(item => item.user_id == userId).nick_name;
      tableData.value[index] = {
        userId: userId,
        userName: label,
        userType: type,
        groupLeaderDeptName: res.data.groupLeaderDeptName,
        groupLeaderPostName: res.data.groupLeaderPostName
      }
    }
  })
  console.log(tableUpdateData1);
}

function getDeptAndPostByUserIdM(userId, form) {
  getDeptAndPostByUserId({userId}).then((res) => {
    if (res.code == 200) {
      form.groupLeaderDeptName = res.data.groupLeaderDeptName;
      form.groupLeaderPostName = res.data.groupLeaderPostName;
    }
  })
}


function getUserM() {
  getUsers().then((res) => {
    users.value = res.data;
    console.log("users", users);
  })
}

function onSubmit() {
  proxy.$refs["classRef"].validate(valid => {
    if (valid) {
      classForm.value.fileList = fileList;
      addClass(classForm.value).then(res => {
        if (res.code === 200) {
          classFormRest();
          proxy.$modal.msgSuccess("保存成功");
          getList();
        }
      })
    }
  });
}

function getList() {
  list(classParamForm.value).then(response => {
    tableData.value = response.rows;
    total.value = response.total;
  });
}

function tableRowClassName({row, rowIndex}) {
  row.index = rowIndex;
}

/** 表单重置 */
function classFormRest() {
  classForm.value = {
    specializedClassName: undefined,
    groupLeaderId: undefined
  };
  fileList.value = [];
  proxy.resetForm("classRef");
}

function classParamFormRest() {
  classParamForm.value = {
    specializedClassName: undefined,
    groupLeaderId: undefined,
  };
  proxy.resetForm("systemParamRef");
  getList();
}

const handleRemove = (file) => {

}

const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.sid);
}

const handleUpdateSelectionChange = (selection) => {
  console.log(selection)
}

const handlePreview = (uploadFile) => {
  console.log(uploadFile)
}

const handleExceed = () => {

}

const beforeRemove = () => {

}

getUserM();
getList();
</script>
<style scoped lang="scss">
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.app-container {
  background-color: #f2f2f2;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.btnWidth {
  width: 80px;
}

</style>
